package org.bridgen.runtime.util;

/**
 * Bridgit is covered by the new BSD License. 
 * You should have received a copy of the new BSD license with Bridgit.
 * 
 * @author Emma Söderberg <emma add cs.lth.se>
 * Copyright (c) 2009
 */

public class Interval {
	protected int start;
	protected int end;

	public Interval(int start, int end) {
		this.start = start;
		this.end = end;
	}

	public int getStart() {
		return start;
	}

	public int getEnd() {
		return end;
	}

	public static Interval merge(Interval intervalA, Interval intervalB) {
		int start = intervalA.getStart();
		if (intervalB.getStart() < start) {
			start = intervalB.getStart();
		}
		int end = intervalB.getEnd();
		if (intervalA.getEnd() > end) {
			end = intervalA.getEnd();
		}
		return new Interval(start, end);
	}

	public boolean inside(int offset) {
		return start <= offset && offset < end;
	}

	public String toString() {
		return "[" + start + "-" + end + "]";
	}

	public Interval clone() {
		return new Interval(start, end);
	}

	public void pushRight(int offset) {
		start += offset;
		end += offset;
	}

	public void mergeWith(Interval interval) {
		if (end+1 == interval.start) {
			end = interval.end;
		} else {
			
			/*
			 *  There's no valid intervals for the SGLR nodes 
			throw new Error("Can only merge to consecutive intervals; first (start=" + 
					start + ",end=" + end + ") second (start=" + start + ",end=" + end + ")");
			*/
		}
	}
	
	public static class Start extends Interval {
		public Start() {
			super(-1, -1);
		}	
		public String toString() {
			return "[start]";
		}
		public Start clone() {
			return new Start();
		}	
	}
	
	public static class End extends Interval {
		public End(int maxOffset) {
			super(maxOffset+1, maxOffset+1);
		}	
		public String toString() {
			return "[end]";
		}
		public End clone() {
			return new End(start);
		}	
	}

	public int getLength() {
		return end - start;
	}

}
